﻿using System;
using System.Media;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Rabbit.Modal;
using Rabbit.Utils;
using Rabbit.BusinessLogicLayer;

namespace MicroBlogClient
{
    /// <summary>
    /// Interaction logic for UCSettings.xaml
    /// </summary>
    public partial class UCSettings : UserControl
    {
        #region Event
        public static RoutedEvent OnSettingsSavedEvent = EventManager.RegisterRoutedEvent(
            "OnSettingsSaved", RoutingStrategy.Bubble, typeof(OneValueEventHandler<UserSettings>), typeof(UCSettings));
        public event OneValueEventHandler<UserSettings> OnSettingsSaved
        {
            add { AddHandler(OnSettingsSavedEvent, value); }
            remove { RemoveHandler(OnSettingsSavedEvent, value); }
        }

        public static RoutedEvent OnMainWindowOpacityChangedEvent = EventManager.RegisterRoutedEvent(
           "OnMainWindowOpacityChanged", RoutingStrategy.Bubble, typeof(OneValueEventHandler<double>), typeof(UCSettings));

        public event OneValueEventHandler<double> OnMainWindowOpacityChanged
        {
            add { AddHandler(OnMainWindowOpacityChangedEvent, value); }
            remove { RemoveHandler(OnMainWindowOpacityChangedEvent, value); }
        }

        public static RoutedEvent OnSettingsCancelEvent = EventManager.RegisterRoutedEvent(
            "OnSettingsCancel", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(UCSettings));

        public event RoutedEventHandler OnSettingsCancel
        {
            add { AddHandler(OnSettingsCancelEvent, value); }
            remove { RemoveHandler(OnSettingsCancelEvent, value); }
        }

        public static RoutedEvent OnMainWindowBackgroundOpacityChangedEvent = EventManager.RegisterRoutedEvent("OnMainWindowBackgroundOpacityChanged",
             RoutingStrategy.Bubble, typeof(OneValueEventHandler<double>), typeof(UCSettings));
        public event OneValueEventHandler<double> OnMainWindowBackgroundOpacityChanged
        {
            add { AddHandler(OnMainWindowBackgroundOpacityChangedEvent, value); }
            remove { RemoveHandler(OnMainWindowBackgroundOpacityChangedEvent, value); }
        }
        #endregion

        public UserSettings MySettings { get; set; }
        Properties.Settings settings = new Properties.Settings();
        long UserID = UserBL.CurrentUser.Id;
        public UCSettings()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(UCSettings_Loaded);
        }

        private void UserControl_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if ((bool)e.NewValue)
            {
                settings.Reload();

                MySettings = settings.UserList.Find(u => u.UserID == UserID);
                txtCaptureScreenHotKey.ClearInvalidInformation();
                txtGetCommentHotKey.ClearInvalidInformation();
                txtGetLetterHotKey.ClearInvalidInformation();
                txtGetStatusHotKey.ClearInvalidInformation();
                txtMetionedMeHotKey.ClearInvalidInformation();
                DataContext = MySettings;
            }
        }

        void UCSettings_Loaded(object sender, RoutedEventArgs e)
        {
            cmbTheme.ItemsSource = Rabbit.Themes.ThemeManager.GetThemeList();
            sldMessageUpdateInterval.Maximum = Configuration.MaxMessageUpdateIntervalUserCanSet;
            sldMessageUpdateInterval.Minimum = Configuration.MinMessageUpdateIntervalUserCanSet;

            MySettings = settings.UserList.Find(u => u.UserID == UserID);
            DataContext = MySettings;
        }

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            //load orignal settings, and reset the data context 
            RaiseEvent(new RoutedEventArgs(OnSettingsCancelEvent));
            this.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            string captureHotKey = MySettings.CaptureScreenHotKey;
            string commenHotKey = MySettings.GetCommentHotKey;
            string letterHotKey = MySettings.GetLetterHotKey;
            string metionedMeHotKey = MySettings.GetMetionedMeHotKey;
            string statusHotKey = MySettings.GetStatusHotKey;

            txtCaptureScreenHotKey.ClearInvalidInformation();
            txtGetCommentHotKey.ClearInvalidInformation();
            txtGetLetterHotKey.ClearInvalidInformation();
            txtMetionedMeHotKey.ClearInvalidInformation();

            if (captureHotKey != "无"
                && (captureHotKey == commenHotKey
                || captureHotKey == letterHotKey
                || captureHotKey == metionedMeHotKey
                || captureHotKey == statusHotKey)
                )
            {
                txtCaptureScreenHotKey.SetHotKeyInvalid();
                return;
            }

            if (commenHotKey != "无"
                && (commenHotKey == captureHotKey
                || commenHotKey == letterHotKey
                || commenHotKey == metionedMeHotKey
                || commenHotKey == statusHotKey
                )
                )
            {
                txtGetCommentHotKey.SetHotKeyInvalid();
                return;
            }

            if (letterHotKey != "无"
               && (letterHotKey == captureHotKey
               || letterHotKey == commenHotKey
               || letterHotKey == metionedMeHotKey
               || letterHotKey == statusHotKey
               )
               )
            {
                txtGetLetterHotKey.SetHotKeyInvalid();
                return;
            }

            if (metionedMeHotKey != "无"
              && (metionedMeHotKey == captureHotKey
              || metionedMeHotKey == commenHotKey
              || metionedMeHotKey == letterHotKey
              || metionedMeHotKey == statusHotKey
              )
              )
            {
                txtMetionedMeHotKey.SetHotKeyInvalid();
                return;
            }

            OneValueEventArgs<UserSettings> args = new OneValueEventArgs<UserSettings>(OnSettingsSavedEvent);
            args.Value = MySettings;

            RaiseEvent(args);
        }

        private void sldMainWindowOpacity_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            OneValueEventArgs<double> args = new OneValueEventArgs<double>(OnMainWindowOpacityChangedEvent);
            args.Value = e.NewValue;
            RaiseEvent(args);
        }

        private void sldMainWindowBackgroundOpacity_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            OneValueEventArgs<double> args = new OneValueEventArgs<double>(OnMainWindowBackgroundOpacityChangedEvent);
            args.Value = e.NewValue;
            RaiseEvent(args);
        }

        private void btnReset_Click(object sender, RoutedEventArgs e)
        {
            settings.Reload();

            MySettings.PopupForMetionedMe = settings.PopupForMetionedMe;
            MySettings.PopupForNewComment = settings.PopupForNewComment;
            MySettings.PopupForNewStatus = settings.PopupForNewStatus;
            MySettings.PopupForNewLetter = settings.PopupForNewLetter;
            MySettings.Theme = settings.Theme;
            MySettings.HelpPublicizing = settings.HelpPublicizing;
            MySettings.UpdateInterval = settings.UpdateInterval;
            MySettings.MainWindowOpacity = settings.MainWindowOpacity;
            MySettings.MainWindowBackgroundOpacity = settings.MainWindowBackgroundOpacity;
            MySettings.PopupMessageShowTime = settings.PopupMessageShowTime;
            MySettings.IsPlayingSound = settings.IsPlayingSound;
            MySettings.IsTwinkleSysTrayIcon = settings.IsTwinkleSysTrayIcon;
            MySettings.CaptureScreenHotKey = settings.CaptureScreenHotKey;
            MySettings.GetLetterHotKey = settings.GetLetterHotKey;
            MySettings.GetMetionedMeHotKey = settings.GetMetionedMeHotKey;
            MySettings.GetStatusHotKey = settings.GetStatusHotKey;
            MySettings.GetCommentHotKey = settings.GetCommentHotKey;
        }

        private void PlaySound_Click(object sender, RoutedEventArgs e)
        {
            (App.Current.MainWindow as MainWindow).Player.Play();
        }

        private void cmbTheme_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            this.Dispatcher.BeginInvoke(new Action(() =>
            {
                App.Current.Resources.MergedDictionaries.Clear();
                App.Current.Resources.MergedDictionaries.Add(Rabbit.Themes.ThemeManager.GetTheme(MySettings.Theme));
            }), System.Windows.Threading.DispatcherPriority.Background);
        }

        private void HotKeyGeneratorTextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            TextBox temp = sender as TextBox;
            temp.SelectionStart = temp.Text.Length;
            e.Handled = true;
        }
    }
}